// my.js
import { getUserInfo as fetchUserInfo,updateUserInfo } from '../../Service/userInfoService';
import { uploadFileBySDK } from '../../Service/uploadService';
const appInstance = getApp();
Page({
  data: {
    avatarUrl: '/static/define-user.png',
    nickname: '匿名用户', 
  },  
  get_HC_collection: function () {
    wx.navigateTo({
      url: '/Not-tabbar/heart/heart',
    });
  },
  get_HC_upload: function () {
    wx.navigateTo({
      url: '/Not-tabbar/hc-upload/hc-upload',
    });
  },

  
  async onChooseAvatar(e) {
    const filePath = e.detail.avatarUrl; // 获取选择的头像路径
    try {
      const uploadedUrl = await uploadFileBySDK(filePath, 'avatar');
      this.setData({
        avatarUrl: uploadedUrl.path
      });
      console.log('知晓云图片路径',this.data.avatarUrl.path);
      this.saveUserInfo(); // 保存到本地
      this.updateUserInfoInServer(); // 更新到服务器
    } catch (error) {
      console.error('头像上传失败', error);
    }
  },
  
  onChooseNickname(e) {
    this.setData({
      nickname: e.detail.value
    });
    this.saveUserInfo();
  },
  
  saveUserInfo() {
    wx.setStorage({
      key: 'userInfo',
      
      data: {
        avatarUrl: this.data.avatarUrl,
        nickname: this.data.nickname
      },
      success: () => {
        console.log('用户信息保存成功');
        this.updateUserInfoInServer();
      },
      fail: err => {
        console.error('用户信息保存失败', err);
      }
    });
  },
  async updateUserInfoInServer() {
    const userId = wx.getStorageSync('userId'); // 获取 userId
    if (!userId) {
      console.error('未找到 userId');
      return;
    }
    const updateData = {
      nickname: this.data.nickname,
      avatarUrl: this.data.avatarUrl // 确保字段名称与服务端一致
    };
    try {
      const success = await updateUserInfo(userId, updateData);
      if (success) {
        console.log('用户信息更新成功');
      } else {
        console.error('用户信息更新失败');
      }
    } catch (error) {
      console.error('用户信息更新失败', error);
    }
  },
 
  
  async getUserInfo() {
    const userId = wx.getStorageSync('userId');
    console.log('userId',userId);
    if (!userId) {
      console.error('未找到 userId');
      return;
    }
    try {
      const userInfo = await fetchUserInfo(userId);
      if (userInfo.avatar_url && userInfo.nickname) {
        this.setData({
          avatarUrl: userInfo.avatar_url,
          nickname: userInfo.nickname
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '请先授权微信头像与微信昵称',
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#17cc84',
          success: res => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/authorize/authorize' // 导航到授权页面
              });
            }
          }
        });
      }
    } catch (error) {
      console.error('获取用户信息失败', error);
      wx.showModal({
        title: '提示',
        content: '获取用户信息失败，请重试',
        showCancel: false,
        confirmText: '确定',
        confirmColor: '#17cc84'
      });
    }
  },

 
  onShow() {
    if (!appInstance.checkTokenValidity()) {
      // Token 已过期或不存在，已重新登录
      console.log('Token expired, re-login in progress');
    } else {
      console.log('Token is valid');
    }
    this.getUserInfo();
  }
});
